<script setup lang="ts">
import { onMounted, ref, toRaw, watch, computed } from "vue";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";
import { useLogic } from "@/views/system/user/logic/logic";
import { getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { handleTree } from "@/utils/tree";
import { ElMessage, ElEmpty } from "element-plus";
import { getDeviceGroupGroupConfigsApi } from "@/api/configs/deviceGroupConfig";
import { LocateSetData } from "@/utils/appCommon/appCommonOptions/aeLocateConfigModel";

// 导入定位模型组件
import LinearComponent from "./component/linear/index.vue";
import PlaneComponent from "./component/plane/index.vue";
import CubeComponent from "./component/cube/index.vue";
import TankBottomComponent from "./component/tankbottom/index.vue";
import CylinderFaceComponent from "./component/cylinderFace/index.vue";
import CylinderBodyComponent from "./component/cylinderBody/index.vue";
import SphereFaceComponent from "./component/sphereFace/index.vue";

const RouteName="locate-analysis"
defineOptions({
  name: RouteName,
});
const router = useRouter();
const route = useRoute();
const storeInfo = useUserStore()
const {deptId}= storeToRefs(storeInfo)
const { t } = useI18n();

// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deptId: deptId.value,  //初始部门id
  deviceGroupId: undefined,
  page:1,
  pageSize:500,
  timeRange: [],
});

// 渲染区域尺寸控制
const defsize = 500
const width = ref(defsize);
const height = ref(defsize);
const viewMode = ref(2); //查看模型类型 3--3d视图 2--2d视图
const renderParams = ref({
  width:defsize,
  height:defsize,
  viewMode:2,
})

const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const deviceNoOptions = ref([])

onMounted(async () => {
  setTimeout(()=>{
    reloadThisPage()
  },5)
})

watch(()=>route.query,(newVal)=>{
  if(route.name==RouteName && newVal){
    if (route.query.deptId && Number(route.query.deptId)>0) {
      searchParams.value.deptId = Number(route.query.deptId);
    }
    setTimeout(()=>{
      reloadThisPage()
    },5)
  }
},{immediate:true,deep:true});

const reloadThisPage = async () => {
  await getDeptTree()
  await reLoadDeviceGroups()
}

const reLoadDeviceGroups = async ()=>{
  const req = new Map;
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi(req)
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
}

const searchFields = ref([
  {
    prop: 'deviceGroupId',
    name: t('datacenter.iotdataPage.deviceGroup'),
    type: 'cascader',
    cascaderOptions: deviceGroupOptions,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: 'timeRange',
    name: t('datacenter.iotdataPage.timeRange'),
    type: 'datetimeRange',
    clearable: true,
    isHidden: false,
  },
  {
    prop: 'deptId',
    name: t('datacenter.iotdataPage.dept'),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
])

const handleChange = (e: any) => {
  console.log(e)
  if(e.deptId != searchParams.value.deptId){
    searchParams.value.deptId = e.deptId
    reLoadDeviceGroups()
  }
  if(e.deviceGroupId != searchParams.value.deviceGroupId){
    searchParams.value.deviceGroupId = e.deviceGroupId
  }
}

const handleSearch = async (e:any) => {
  searchParams.value.page = 1
  console.log(e)
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  const checkres = checkSearchValid()
  if(!checkres){
    return
  }
  await loadConfigData()
}

const checkSearchValid = ()=>{
  return true;
}

const handleReset = (e:any) => {
  console.log(e)
}

// 应用尺寸
const applyDimensions = () => {
  renderParams.value = {
    width: width.value,
    height: height.value,
    viewMode: viewMode.value,
  }
};

// 跳转到分组配置
const jumpToGroupConfig = () => {
  if(!searchParams.value.deviceGroupId){
    ElMessage.warning("请先选择分组")
    return
  }
  // 跳转到分组配置页面
  router.push({
    path: '/configs/deviceGroupConfig',
    query: {
      deviceGroupId:searchParams.value.deviceGroupId,
      destination:"locateSet"
    },
  });
};

const locateSetting = ref<LocateSetData>(null)

// 组件映射关系
const componentMap = {
  line: LinearComponent,
  plane: PlaneComponent,
  cube: CubeComponent,
  tankBottom: TankBottomComponent,
  cylinderFace: CylinderFaceComponent,
  cylinderBody: CylinderBodyComponent,
  sphereFace: SphereFaceComponent
};

// 计算当前应该渲染的组件
const currentComponent = computed(() => {
  if (!locateSetting.value || !locateSetting.value.config || !locateSetting.value.config.locateModel) {
    return null;
  }
  return componentMap[locateSetting.value.config.locateModel] || null;
});

// 加载配置数据
const loadConfigData = async () => {
  if (!searchParams.value.deviceGroupId) return;

  locateSetting.value = null
  try {
    const res = await getDeviceGroupGroupConfigsApi({
      deviceGroupId: searchParams.value.deviceGroupId,
      groupName: "locateSet"
    });

    if (res.code === 0 && res.data?.configs) {
      try {
        const configData = JSON.parse(res.data.configs[0]?.configValue || '{}');
        if(configData){
          // 更新配置数据
          locateSetting.value = configData;
        }
      } catch (e) {
        ElMessage.warning('解析配置数据失败:'+e.message);
      }
    }
  } catch (error) {
    console.error('加载配置失败', error);
    ElMessage.error('加载配置失败');
  } finally {
  }
};

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=6
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>
  <!--    内容区域-->
  <el-card shadow="never" style="margin-top: 20px;">
    <template #header>
      <div class="render-card-header">
        <div class="input-group">
          宽度(px):<el-input-number
            v-model.number="width"
            :min="300"
            :max="2000"
            :step="50"
            style="width: 180px; margin-right: 10px;"
          />
          高度(px):<el-input-number
            v-model.number="height"
            :min="300"
            :max="2000"
            :step="50"
            style="width: 180px; margin-right: 10px;"
          />
          视图：<el-select v-model="viewMode" placeholder="" style="width:150px;">
                  <el-option :label="'2D视图'" :value="2" />
                  <el-option :label="'3D视图'" :value="3" />
                </el-select>
          <el-button type="primary" @click="applyDimensions">应用</el-button>
          <el-button @click="jumpToGroupConfig">查看配置</el-button>
        </div>
      </div>
    </template>
    <div class="render-area" :style="{ width: renderParams.width + 'px', height: renderParams.height + 'px' }">
      <component
        v-if="currentComponent"
        :is="currentComponent"
        :locate-setting="locateSetting"
        :render-params="renderParams"
        :search-params="searchParams"
      />
      <div v-else class="empty-state">
        <el-empty description="暂无定位配置数据" :image-size="100" />
      </div>
    </div>
  </el-card>
  </el-card>
</template>

<style scoped lang="scss">
.render-card-header {
  width: 100%;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.render-area {
  background-color: #f0f2f5;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  & > * {
    width: 100%;
    height: 100%;
  }
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

